package com.timguan.render.web.biz;

import com.timguan.render.api.api.B2CMallServiceReturnCode;
import com.timguan.render.api.api.backend.CMSPageService;
import com.timguan.render.api.api.backend.CMSRouteService;
import com.timguan.render.api.constants.ResourceTypeEnum;
import com.timguan.render.api.entity.cms.CMSPage;
import com.timguan.render.api.entity.cms.CMSResourceConfig;
import com.timguan.render.service.common.B2CMallConstants;
import com.timguan.render.service.common.B2CMallServiceConfig;
import com.timguan.render.web.common.App;
import com.timguan.render.web.common.TopicTypeMissmatchException;
import net.pocrd.entity.ServiceException;
import net.pocrd.entity.ServiceRuntimeException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

/**
 * Created by guankaiqiang on 2015/3/22.
 */
public class CMSTopicBiz {
    private static final Logger logger = LoggerFactory.getLogger(CMSTopicBiz.class);
    @Autowired
    private CMSRouteService cmsTopicServiceImpl;
    @Autowired
    private CMSPageService cmsPageServiceImpl;

    /**
     * 获取专题信息
     *
     * @param srcActivityId
     * @param app
     * @param appVersion
     */
    public CMSPage getCmsPage(int srcActivityId, App app, String appVersion) {
        CMSPage cmsPage = getCmsPage(null, srcActivityId, app, appVersion);
        if (cmsPage == null) {
            logger.info("未知专题,topic:{}", srcActivityId);
            throw new ServiceRuntimeException(B2CMallServiceReturnCode.TOPIC_NOT_FOUND, "未知专题,topic:" + srcActivityId);
        }
        return cmsPage;
    }

    /**
     * 获取专题信息
     *
     * @param srcUri
     * @param app
     * @param appVersion
     */
    public CMSPage getCmsPage(String srcUri, App app, String appVersion) {
        CMSPage cmsPage = getCmsPage(srcUri, 0, app, appVersion);
        if (cmsPage == null) {
            logger.info("未知专题,topic:{}", srcUri);
            throw new ServiceRuntimeException(B2CMallServiceReturnCode.TOPIC_NOT_FOUND, "未知专题,topic:" + srcUri);
        }
        return cmsPage;
    }

    /**
     * 获取专题信息
     *
     * @param srcUri
     * @param srcActivityId
     * @param app
     * @param appVersion
     */
    private CMSPage getCmsPage(String srcUri, int srcActivityId, App app, String appVersion) {
        CMSPage cmsPage = null;
        if (StringUtils.isNotBlank(srcUri) || srcActivityId > 0) {
            try {
                //非PC都认为访问入口是H5_RENDER
                cmsPage = cmsTopicServiceImpl.getCmsPage(
                        App.B2CPC == app ? CMSRouteService.AccessPlatform.PC_RENDER : CMSRouteService.AccessPlatform.H5_RENDER,
                        srcUri, srcActivityId, app.getAppid(), appVersion);
            } catch (Throwable e) {
                logger.error("获取专题出错", e);
                throw new ServiceRuntimeException(B2CMallServiceReturnCode.TOPIC_NOT_FOUND, "获取专题出错,topic:" + srcActivityId);
            }
            if (cmsPage != null) {
                if (cmsPage.isNeed302Redirect()) {
                    Exception exception = new TopicTypeMissmatchException(TopicTypeMissmatchException.RedirectType.REDIRECT_302,
                            cmsPage.getRedirectUrl());
                    throw new ServiceRuntimeException(B2CMallServiceReturnCode.TOPIC_TYPE_NOT_MATCH, exception);
                } else if (cmsPage.isNeedInvokeRedirect()) {
                    Exception exception = new TopicTypeMissmatchException(TopicTypeMissmatchException.RedirectType.REDIRECT_INVOKE,
                            cmsPage.getRedirectUrl());
                    throw new ServiceRuntimeException(B2CMallServiceReturnCode.TOPIC_TYPE_NOT_MATCH, exception);
                } else {
                    if (App.B2CPC == app && cmsPage.getType() != B2CMallConstants.PC_PAGE_TYPE) {
                        throw new ServiceRuntimeException(B2CMallServiceReturnCode.TOPIC_TYPE_NOT_MATCH);
                    } else if (App.B2CPC != app && cmsPage.getType() == B2CMallConstants.PC_PAGE_TYPE) {
                        throw new ServiceRuntimeException(B2CMallServiceReturnCode.TOPIC_TYPE_NOT_MATCH);
                    }
                }
            }
        }
        return cmsPage;
    }

    /**
     * 根据pagename获取页面内容
     *
     * @param pageId
     * @param app
     */
    public Map<String, List<List<Object>>> getDataOfPage(int pageId, App app) {
        Map<String, List<List<Object>>> result = null;
        try {
            result = cmsPageServiceImpl.getDataOfPage(pageId, app.getAppid());
        } catch (ServiceException e) {
            logger.error("获取页面信息出错,pageId:" + pageId, e);
        }
        return result;
    }

    /**
     * 查询page对应的Header and Footer
     *
     * @param pageId
     */

    public Resources getResources(int pageId) {
        Resources resources = null;
        try {
            resources = new Resources(cmsPageServiceImpl.getResourceConfigsOfPage(pageId));
        } catch (ServiceException e) {
            logger.error("获取页面资源信息出错,pageId:" + pageId, e);
        }
        return resources;
    }

    public static class Resources {
        private String header;
        private String footer;
        private String h5commoncss;
        private String h5commonjs;
        private String pccommoncss;
        private String pccommonjs;

        private void setH5commoncss(String version) {
            String tmp = B2CMallConstants.CMS_H5_COMMON_CSS_TPL
                    .replaceAll(B2CMallConstants.CMS_BASE_RESOURCE_PREFIX_PLACEHOLDER_REGEX, B2CMallServiceConfig.getInstance().getH5BaseResource() + "/" + version);
            this.h5commoncss = tmp;
        }

        private void setH5commonjs(String version) {
            String tmp = B2CMallConstants.CMS_H5_COMMON_JS_TPL
                    .replaceAll(B2CMallConstants.CMS_BASE_RESOURCE_PREFIX_PLACEHOLDER_REGEX, B2CMallServiceConfig.getInstance().getH5BaseResource() + "/" + version);
            this.h5commonjs = tmp;
        }

        public void setPccommoncss(String version) {
            String tmp = B2CMallConstants.CMS_PC_COMMON_CSS_TPL
                    .replaceAll(B2CMallConstants.CMS_BASE_RESOURCE_PREFIX_PLACEHOLDER_REGEX, B2CMallServiceConfig.getInstance().getPcBaseResource() + "/" + version);
            this.pccommoncss = tmp;
        }

        public void setPccommonjs(String version) {
            String tmp = B2CMallConstants.CMS_PC_COMMON_JS_TPL
                    .replaceAll(B2CMallConstants.CMS_BASE_RESOURCE_PREFIX_PLACEHOLDER_REGEX, B2CMallServiceConfig.getInstance().getPcBaseResource() + "/" + version);
            this.pccommonjs = tmp;
        }

        public Resources(List<CMSResourceConfig> cmsResourceConfigs) {
            if (cmsResourceConfigs != null && cmsResourceConfigs.size() != 0) {
                for (CMSResourceConfig cmsResourceConfig : cmsResourceConfigs) {
                    if (cmsResourceConfig.getResType() == ResourceTypeEnum.PC_HEADER || cmsResourceConfig.getResType() == ResourceTypeEnum.H5_HEADER) {
                        header = cmsResourceConfig.getValue();
                    } else if (cmsResourceConfig.getResType() == ResourceTypeEnum.PC_FOOTER || cmsResourceConfig.getResType() == ResourceTypeEnum.H5_FOOTER) {
                        footer = cmsResourceConfig.getValue();
                    } else if (cmsResourceConfig.getResType() == ResourceTypeEnum.H5_BASE_RESOURCE_VERSION) {
                        setH5commoncss(cmsResourceConfig.getValue());
                        setH5commonjs(cmsResourceConfig.getValue());
                    } else if (cmsResourceConfig.getResType() == ResourceTypeEnum.PC_BASE_RESOURCE_VERSION) {
                        setPccommoncss(cmsResourceConfig.getValue());
                        setPccommonjs(cmsResourceConfig.getValue());
                    }
                }
            }
        }

        public String getHeader() {
            return header;
        }

        public void setHeader(String header) {
            this.header = header;
        }

        public String getFooter() {
            return footer;
        }

        public void setFooter(String footer) {
            this.footer = footer;
        }

        public String getH5commoncss() {
            return h5commoncss;
        }

        public String getH5commonjs() {
            return h5commonjs;
        }

        public String getPccommoncss() {
            return pccommoncss;
        }

        public String getPccommonjs() {
            return pccommonjs;
        }
    }
}
